package com.jfinal.template;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;

import org.apache.commons.io.IOUtils;

/**
 * Created by wangyan on 2017/7/13.
 */
public class ClasspathLoaderStringSource implements IStringSource{
    private String finalFileName;
    private String fileName;
    private String encoding;
    private long lastModified;
    private ClassLoader classpathResourceLoader;

    public ClasspathLoaderStringSource(String baseTemplatePath, String fileName, String encoding) {
        this.finalFileName = buildFinalFileName(baseTemplatePath, fileName);
        this.fileName = fileName;
        this.encoding= encoding;
        classpathResourceLoader= this.getClass().getClassLoader();
    }

    public boolean isModified() {
        URL url = classpathResourceLoader.getResource(finalFileName);
    	try {
			return lastModified !=url.openConnection().getLastModified();
		} catch (IOException e) {
			return false;
		}
    }

    public StringBuilder getContent() {
		InputStream stream = classpathResourceLoader.getResourceAsStream(finalFileName);
        try{
            if (stream == null){
                throw new Exception("Cannot find file " + finalFileName);
            }
            URL url = classpathResourceLoader.getResource(finalFileName);
    		// 极为重要，否则在模板文件被修改后会不断 reload 模板文件
    		this.lastModified = url.openConnection().getLastModified();
            return new StringBuilder(IOUtils.toString(stream,encoding));
        }catch (Exception e) {
            e.printStackTrace();
        }
		return null;
    }

    public String getKey() {
		return fileName;
	}
	
	public String getEncoding() {
		return encoding;
	}
	
	public String getFinalFileName() {
		return finalFileName;
	}
	
	public String getFileName() {
		return fileName;
	}
    private String buildFinalFileName(String baseTemplatePath, String fileName) {
		char firstChar = fileName.charAt(0);
		String finalFileName;
		if (firstChar == '/' || firstChar == '\\') {
			finalFileName = baseTemplatePath + fileName;
		} else {
			finalFileName = baseTemplatePath + File.separator + fileName;
		}
		return finalFileName;
	}
	
	public String toString() {
		StringBuilder sb = new StringBuilder();
		sb.append("File name: ").append(fileName).append("\n");
		sb.append("Final file name: ").append(finalFileName).append("\n");
		sb.append("Last modified: ").append(lastModified).append("\n");
		return sb.toString();
	}
}
